package SpringCloudBase.controller;

import SpringCloudBase.vo.UserVO;
import com.netflix.discovery.EurekaClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @ClassName ConsumerOrderController
 * @Description : 功能说明
 * @Author : LiangT
 * @Date : 2020/3/31 11:53
 */
@RestController
public class ConsumerOrderController {
    @Value("${userUrl}")
    private String userUrl="http://127.0.0.1:7900";

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private EurekaClient eurekaClient;
    @GetMapping("/order/{id}")
    public UserVO getUser(@PathVariable Long id){
        String url = userUrl +"/user/"+id;
//        验证EurekaClient访问其他服务
        url = eurekaClient.getNextServerFromEureka("PROVIDER-USER",true).getHomePageUrl()+"/user/"+id;
        System.out.println("请求访问地址="+url);
//        验证使用Ribbon访问其他服务
//        url="http://PROVIDER-USER/user/"+id;
        return restTemplate.getForObject(url,UserVO.class);
    }

    @GetMapping("/test")
    public  String  test(){
        //查找对应服务示例，通过负载均衡算法返回一个
        ServiceInstance choose1 = loadBalancerClient.choose("PROVIDER-USER");
        String s1 = "1111:"+choose1.getServiceId()+":"+choose1.getHost()+":"+choose1.getPort();
        System.out.println("s1:"+s1);
        ServiceInstance choose2 = loadBalancerClient.choose("PROVIDER-USER1");
        String s2 = "2222:"+choose2.getServiceId()+":"+choose2.getHost()+":"+choose2.getPort();
        System.out.println("s2:"+s2);
        return s1;
    }

}
